package com.uml.umlwork.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uml.umlwork.dto.classs.AddClassDTO;
import com.uml.umlwork.entity.Class;
import com.uml.umlwork.mapper.ClassMapper;
import com.uml.umlwork.service.ClassService;
import com.uml.umlwork.utils.DataUtil;
import com.uml.umlwork.utils.PageResult;
import com.uml.umlwork.vo.clazz.ClassTeacherVO;
import com.uml.umlwork.vo.clazz.ClassVO;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 少枫
 * @date 2021/1/5
 */
@Service
public class ClassServiceImpl implements ClassService {

    private final ClassMapper classMapper;

    public ClassServiceImpl(ClassMapper classMapper) {
        this.classMapper = classMapper;
    }

    @Override
    public PageResult<ClassTeacherVO> getClassByTeacherId(Long current, Long size, Integer teacherId) {

        Page<ClassTeacherVO> classes = classMapper.getClassByTeacherId(new Page<>(current, size),
                (new QueryWrapper<Class>()).lambda().eq(Class::getTeacherId, teacherId));

        PageResult<ClassTeacherVO> result = new PageResult<>();
        DataUtil.pageFormat(classes, result);

        return result;
    }

    @Override
    public List<Class> getAllClassesByCourseId(Integer courseId) {
        return classMapper.selectList(new QueryWrapper<Class>().eq("course_id", courseId));
    }

    @Override
    public void createClass(AddClassDTO dto) {
        Class clazz = new Class();
        clazz.setCourseId(dto.getCourseId())
                .setTuition(dto.getTuition())
                .setTeacherId(dto.getTeacherId())
                .setIsAnnounce(true)
                .setStartDate(dto.getStartDate());
        classMapper.insert(clazz);
    }

    @Override
    public List<ClassVO> getMyClass(String id) {
        return classMapper.selectList(new QueryWrapper<Class>().eq("teacher_id", id))
                .stream().map(ClassVO::new).collect(Collectors.toList());
    }

    @Override
    public void updateClassStatus(Integer id, Integer open) {
        Class clazz = getClassById(id);
        clazz.setIsAnnounce(open.equals(1));
        classMapper.updateById(clazz);
    }


    private Class getClassById(Integer id) {
        return Optional.ofNullable(classMapper.selectById(id))
                .orElseThrow(() -> new RuntimeException("该id:" + id + "有误"));
    }
}
